<template>
  <div class="listContent" ref="mainCon">
    <div class="mainCon">
      <el-row
        class="toolbar searchInputWidth"
        style="padding-bottom: 0; position: relative"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="事项类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.typeId"
                filterable
                placeholder="请选择"
                clearable
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="(item, index) in eventTypeArr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="巡查事项">
              <el-input
                v-model="filterField.item"
                placeholder="请输入巡查事项内容"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-form-item>
                        <el-button
                            type="primary"
                            icon="icon iconfont iconchazhao1"
                            @click="searchList"
                            class="commonBtn"
                        ></el-button>
                    </el-form-item> -->
          <el-form-item label="">
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <exportBtn
              v-if="!isShowAdd"
              :dataLen="tableList.length"
              :filterField="filterField"
              :api="api"
            ></exportBtn>
            <!-- <el-button
                            v-show="isShowAdd"
                            type="primary"
                            class="commonBut saveBtn"
                            icon="icon iconfont icontianjia"
                            @click="addInspectionItems"
                            ><span class="opetareText">添加巡查事项</span></el-button> -->
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <exportBtn
            :dataLen="tableList.length"
            :filterField="filterField"
            :api="api"
          ></exportBtn>
          <el-button
            type="primary"
            class="commonBut saveBtn"
            icon="icon iconfont icontianjia"
            @click="addInspectionItems"
            ><span class="opetareText">添加巡查事项</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          :span-method="objectSpanMethod"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          border
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="type"
            label="事项类型"
            align="left"
            min-width="28%"
          ></el-table-column>
          <el-table-column
            prop="item"
            label="巡查事项"
            align="center"
            :formatter="formatTd"
            min-width="40%"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="left"
            :formatter="formatTd"
            width="180"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-if="isShowDetail"
                @click="toDetail(scope.row)"
                >查看</el-link
              >
              <el-link
                type="primary"
                v-if="isShowUpdate"
                @click="updateInspectionItems(scope.row)"
                >修改</el-link
              >
              <el-link
                type="primary"
                v-if="isShowDelete"
                @click="deleteInspection(scope.row)"
                >删除</el-link
              >
              <span v-if="!isShowUpdate && !isShowDelete && !isShowDetail"
                >--</span
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>
        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <InspectionDialog
      v-if="dialogVisible"
      :dialogVisible="dialogVisible"
      :inspectionItemsDetail="inspectionItemsDetail"
      :dialogType="actionType"
      @closeDialog="closeDialog"
    ></InspectionDialog>
    <el-dialog
      title="提示"
      :visible.sync="delDialogVisible"
      width="640px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <span>请确认是否删除该条信息？</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="btn cancel" @click="delDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" class="btn save" @click="delInspectionItems()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="巡查事项详情"
      :visible.sync="detailDialogVisible"
      width="640px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div class="mrT8">
        <div class="itemDetail">
          <div class="subTitle">事项类别：</div>
          <div class="subContent">
            {{ inspectionItemsDetail.type }}
          </div>
        </div>
        <div class="itemDetail">
          <div class="subTitle">巡查事项：</div>
          <div class="subContent">
            {{ inspectionItemsDetail.item }}
          </div>
        </div>
        <div class="itemDetail">
          <div class="subTitle">巡查结果：</div>
          <div class="subContent">
            {{ inspectionItemsDetail.resultTypeDesc }}
          </div>
        </div>
        <div class="itemDetail">
          <div class="subTitle" style="line-height: 36px">结果详情：</div>
          <div class="subContent">
            <template
              v-if="
                inspectionItemsDetail.resultType === 'SINGLE_CHOOSE' ||
                inspectionItemsDetail.resultType === 'MULTIPLE_CHOOSE'
              "
            >
              <p
                style="margin-bottom: 16px"
                v-for="(v, i) in inspectionItemsDetail.value"
                :key="i"
              >
                <el-radio
                  disabled
                  label=""
                  v-if="inspectionItemsDetail.resultType === 'SINGLE_CHOOSE'"
                ></el-radio>
                <el-checkbox
                  disabled
                  label=""
                  v-if="inspectionItemsDetail.resultType === 'MULTIPLE_CHOOSE'"
                ></el-checkbox>
                <el-input
                  type="text"
                  disabled
                  v-model="inspectionItemsDetail.value[i]"
                  class="dialogSingleInp"
                ></el-input>
              </p>
            </template>
            <template v-else-if="inspectionItemsDetail.resultType === 'DATE'">
              <el-date-picker
                type="date"
                disabled
                placeholder="请选择"
                class="dialogSingleHalfInp"
                clearable
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </template>
            <template v-else>
              <el-input type="text" disabled></el-input>&nbsp;{{ unit }}
            </template>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import emptyTable from '@/components/publicCom/emptyTable'
import Pagination from '@/components/publicCom/pagination'
import InspectionDialog from '@/components/patrol/InspectionDialog'

export default {
  name: 'InspectionItemsList',
  components: {
    emptyTable,
    Pagination,
    InspectionDialog,
  },
  data() {
    return {
      hiddleToolBar: false,
      tableHeight: null,
      dialogVisible: false,
      actionType: 'add',
      detailDialogVisible: false,
      delDialogVisible: false,
      inspectionItemsId: '',
      inspectionItemsDetail: {},
      eventTypeArr: [],
      //表格数据
      tableList: [],
      requestUrl: '/api-gov/ipqcItem/base/findItems',
      //搜索条件
      filterField: {
        item: '',
        typeId: '',
      },
      pageSize: 20,
      pageNo: 1,
      isShow: false, //列表加载
      loading: false,
      isShowAdd: false,
      isShowUpdate: false,
      isShowDelete: false,
      isShowDetail: false,
      api: '',
    }
  },
  created() {
    this.getEventType()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getApi()
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:update') > -1
    this.isShowDelete =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:delete') > -1
    this.isShowDetail =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:detail') > -1
  },
  activated() {
    this.getEventType()
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  computed: {
    unit() {
      let unitName = null
      switch (this.inspectionItemsDetail.resultType) {
        case 'TEXT':
          unitName = ''
          break
        case 'POPULATION':
          unitName = '人'
          break
        case 'PERCENTAGE':
          unitName = '%'
          break
        case 'MONEY':
          unitName = '元'
          break
        case 'AMOUNT':
          unitName = '个'
          break
        case 'DAYS':
          unitName = '天'
          break
        case 'HOURS':
          unitName = '小时'
          break
        default:
          break
      }
      return unitName
    },
  },
  methods: {
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 218

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    // 新增巡查事项
    addInspectionItems() {
      this.actionType = 'add'
      this.dialogVisible = true
    },
    closeDialog() {
      this.dialogVisible = false
      this.inspectionItemsDetail = {}
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      })
    },
    // 查看巡查
    async toDetail(row) {
      await this.getEventDetail(row.id)
      this.detailDialogVisible = true
    },
    // 修改巡查事项
    async updateInspectionItems(row) {
      await this.getEventDetail(row.id)
      this.actionType = 'update'
      this.dialogTitle = '修改巡查事项'
      this.dialogVisible = true
    },
    // 删除巡查事项
    deleteInspection(row) {
      // this.delDialogVisible = true;
      this.eventTypeId = row.id
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delInspectionItems()
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
    },
    delInspectionItems() {
      return this.axios({
        method: 'post',
        url: 'api-gov/ipqcItem/base/removeItem',
        data: {
          itemId: this.eventTypeId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message.success('删除成功')
            this.delDialogVisible = false
            this.$nextTick(function () {
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            })
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 获取事项类别
    getEventType() {
      return this.axios({
        method: 'get',
        url: 'api-gov/ipqcType/base/findAllTypes',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.eventTypeArr = results
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 获取事项详情
    getEventDetail(itemId) {
      return this.axios({
        method: 'post',
        url: 'api-gov/ipqcItem/base/itemDetail',
        data: {
          itemId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.inspectionItemsDetail = results
            this.inspectionItemsDetail.value = JSON.parse(results.value)
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 合并行判断条件
    mergeSpan(tableData) {
      let spanArr = []
      let concat = 0
      tableData.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
        } else {
          if (item.typeId === tableData[index - 1].typeId) {
            //需合并相同内容的判断条件
            spanArr[concat]++
            spanArr.push(0)
          } else {
            spanArr.push(1)
            concat = index
          }
        }
      })
      return {
        spanArr,
      }
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.mergeSpan(this.tableList).spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col,
        }
      }
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      // this.mergeSpan(this.tableList);
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    getApi() {
      if (localStorage.getItem('judgeRoleCode') === 'company') {
        this.api = 'api-s/report/export_JC_NC_IPQC_ITEM'
      } else {
        this.api = 'api-s/report/export_JC_CS_IPQC_ITEM'
      }
    },
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #333333;
}
// .wideInput{
//     /deep/ .el-input__inner {
//         width: 270px !important;
//     }
// }
.addEvent {
  position: absolute;
  right: 0;
  top: 0;
}
.itemDetail {
  margin-bottom: 22px;
  .subTitle {
    display: inline-block;
    width: 120px;
    text-align: right;
  }
  .subContent {
    display: inline-block;
    vertical-align: top;
    // width: 390px;
  }
  /deep/ .el-input {
    width: 340px;
  }
  /deep/ .el-radio {
    margin-right: 0;
  }
  /deep/ .el-checkbox {
    margin-right: 10px;
  }
}
@import '../../../static/css/filterArea.less';
.mainCon {
  padding-top: 0;
  padding-bottom: 0;
}
</style>
